<template>
	<view class="page-box">
		<image src="https://wx.2024csnl.com/static/goods/scratch-bg.png" mode="widthFix" class="scratch-bg" />
		<view class="info">
			<swiper style="height: 48rpx;" vertical :autoplay="true" circular :interval="3000" :duration="1000">
				<swiper-item v-for="(v,i) in prizeList" :key="i">
					<view class="swiper-item flex align">
						<image src="https://wx.2024csnl.com/static/goods/laba.png" mode="aspectFill" class="laba" />
						<view class="">{{v.text}}</view>
					</view>
				</swiper-item>
			</swiper>

			<view class="" style="text-align: center;color: black;margin-top: 100rpx;font-size: 32rpx;">刮刮卡一张</view>

			<view class="content">
				<view class="value" v-show="readyState">{{prizeText}}</view>
				<canvas :style="{'width':width+'px','height':height+'px',borderRadius: '10px'}" canvas-id="myCanvas"
					id="myCanvas" @touchstart="onStartGetPrizeMsg" @touchend="touchend" @touchmove="touchmove">
				</canvas>
			</view>
			<!-- <button @click="reset">重置</button> -->
		</view>
		<view class="prize-box">
			<view class="prize-label">每日刮卡抽奖奖品</view>
			<view class="flex align" style="flex-wrap: wrap;">
				<view class="prize-item" v-for="(item,index) in navList" :key="index"
					@click="onSkip(`/pages/draw/prize-detail?id=${allMsg.info.id}&jx=${item.jx}`)">
					<image :src="item.pic" mode="aspectFill" />
					<view class="">{{item.mc}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		startGetPrizeMsg,
		getPrizeMsg
	} from "../../api/index.js"
	export default {
		data() {
			return {
				prizeText: '', //奖品文字
				isRate: null, //是否中奖
				id: null,
				pageType: null,
				ctx: null,
				width: 0,
				height: 0,

				disabled: false, // 是否禁止刮卡
				readyState: false, // 是否开始绘制
				endState: false, // 结束刮卡状态

				watermark: ' ', // 水印文字
				watermarkColor: '#c5c5c5', // 水印文字颜色
				watermarkSize: 14, // 水印文字大小

				title: '刮 奖 区', // 提示文字
				titleColor: '#FFF', // 提示文字颜色
				titleSize: 25, // 提示文字大小

				startX: 0, // 触摸x轴位置
				startY: 0, // 触摸y轴位置
				touchSize: 20, // 触摸画笔大小
				percentage: 50, // 刮开百分之多少的时候开奖
				navList: [], //奖品
				prizeList: [], //中奖列表
				allMsg:{},
			}
		},
		onLoad(opt) {
			this.pageType = opt.pageType
			this.id = opt.id
			this.onGetPrizeMsg()
		},
		onShow() {
			this.$nextTick(() => {
				let content = uni.createSelectorQuery().select(".content");
				content.boundingClientRect((data) => {
					this.width = data.width;
					this.height = data.height;
					this.ctx = uni.createCanvasContext('myCanvas', this);
					setTimeout(e => {
						this.init();
					}, 20);
				}).exec()
			})

		},
		methods: {
			// 抽奖数据
			async onGetPrizeMsg() {
				const res = await getPrizeMsg('s=/ApiChoujiang/index', {
					id: this.id
				})
				const {
					msg,
					data,
					status
				} = res.data
				if (status == 1) {
					this.navList = data.jxarr
					this.prizeList = data.zjlist
					this.rule = data.info.guize
					this.lotteryNums = data.remaindaytimes
					this.allMsg=data
					// console.log(this.lotteryNums, 'rule')

				} else {
					this.showToast(msg)
				}
				// console.log(res, "res---")

			},
			// 获取抽奖结果
			async onStartGetPrizeMsg() {
				const res = await startGetPrizeMsg('s=/ApiChoujiang/index', {
					type: this.pageType,
					id: this.id,
					op: 'getjx'
				})
				// console.log(res, "******")
				const {
					status,
					msg,
					data
				} = res.data
				if (status == 1) {
					this.prizeText = data.jxmc
					this.isRate = data.jx
					this.touchstart(data.jx)
				} else {
					this.disabled = true
					this.readyState = false;
					this.showToast(msg)
				}
			},
			init() {
				this.endState = false;
				this.readyState = false;
				this.ctx.clearRect(0, 0, this.width, this.height); // 清除画布上在该矩形区域内的内容(x,y,宽，高)。
				this.ctx.setFillStyle('#FF7C06'); // 填充颜色
				this.ctx.fillRect(0, 0, this.width, this.height); // 填充区域（x,y,宽,高）
				/**
				 * 绘制文字水印
				 */
				var width = this.watermark.length * this.watermarkSize;
				this.ctx.save(); // 保存当前的绘图上下文。
				this.ctx.rotate(-10 * Math.PI / 180); // 以原点为中心，原点可以用 translate方法修改。顺时针旋转当前坐标轴。多次调用rotate，旋转的角度会叠加。
				let x = 0;
				let y = 0;
				let i = 0;
				while ((x <= this.width * 5 || y <= this.height * 5) && i < 300) {
					this.ctx.setFillStyle(this.watermarkColor); // 填充颜色
					this.ctx.setFontSize(this.watermarkSize); // 设置字体的字号
					this.ctx.fillText(this.watermark, x, y); // 填充的文本（文字，x，y）
					x += width + width * 1.6;
					if (x > this.width && y <= this.height) {
						x = -Math.random() * 100;
						y += this.watermarkSize * 3;
					}
					i++;
				}
				this.ctx.restore(); // 恢复之前保存的绘图上下文。

				/**
				 * 绘制标题
				 */
				this.ctx.setTextAlign("center"); // 用于设置文字的对齐
				this.ctx.setTextBaseline("middle"); // 用于设置文字的水平对齐
				this.ctx.setFillStyle(this.titleColor); // 填充颜色
				this.ctx.setFontSize(this.titleSize); // 设置字体的字号
				this.ctx.fillText(this.title, this.width / 2, this.height / 2); // 填充的文本（文字，x，y）

				this.ctx.draw(); // 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
				this.readyState = true; // 完成绘制
			},
			// 手指触摸动作开始
			touchstart(e) {
				if (this.disabled || this.endState) {
					return;
				}
				console.log(e, "eeeeee")
				// 报错注释了
				// this.startX = e.touches[0].x;
				// this.startY = e.touches[0].y;
			},
			// 手指触摸后移动
			touchmove(e) {
				if (this.disabled || this.endState) {
					return;
				}
				this.ctx.clearRect(this.startX, this.startY, this.touchSize, this.touchSize); // 清除画布上在该矩形区域内的内容(x,y,宽，高)。
				this.ctx.draw(true); // false:本次绘制是否接着上一次绘制，true:保留当前画布上的内容
				//记录移动点位
				this.startX = e.touches[0].x;
				this.startY = e.touches[0].y;
			},
			// 手指触摸动作结束
			touchend(e) {
				if (this.disabled || this.endState) {
					return;
				}
				// 返回一个数组，用来描述 canvas 区域隐含的像素数据，在自定义组件下，第二个参数传入自定义组件实例 this，以操作组件内 <canvas> 组件。
				uni.canvasGetImageData({
					canvasId: 'myCanvas',
					x: 0,
					y: 0,
					width: this.width,
					height: this.height,
					success: (res) => {
						console.log(res);
						let pixels = res.data;
						let transPixels = [];
						for (let i = 0; i < pixels.length; i += 4) {
							if (pixels[i + 3] < 128) {
								transPixels.push(pixels[i + 3]);
							}
						}
						var percent = (transPixels.length / (pixels.length / 4) * 100).toFixed(2);
						if (percent >= this.percentage) {
							this.success();
						}
					},
					fail: (e) => {
						console.log(e);
					},
				}, this);
			},

			// 成功，清除所有图层
			success(e) {
				if (this.endState) {
					return;
				}
				this.endState = true;
				this.ctx.moveTo(0, 0); // 把路径移动到画布中的指定点，不创建线条。用 stroke() 方法来画线条。
				this.ctx.clearRect(0, 0, this.width, this.height); // 清除画布上在该矩形区域内的内容(x,y,宽，高)。
				this.ctx.stroke(); // 画出当前路径的边框。默认颜色色为黑色。
				this.ctx.draw(true);
				if (this.isRate != 0) {

				}
				this.modal()
			},
			async modal(type) {
				const result = await new Promise(resolve => {
					uni.showModal({
						title: this.isRate == 0 ? '很遗憾' : '恭喜你',
						content: this.isRate != 0 ? `抽中${this.prizeText}` : '暂未中奖',
						showCancel: false,
						confirmColor: '#41644A',
						success(msg) {
							resolve(msg)
						}
					});
				})
				if (result.confirm) {
					this.reset()
				}
			},

			// 重置
			reset() {
				this.init();
			},
		}
	}
</script>

<style scoped lang="scss">
	.page-box {
		background-image: linear-gradient(to top, #41644A, #FA7268);
		padding: 20rpx;
		height: 100vh;
		position: relative;

		.scratch-bg {
			width: 710rpx;
			display: block;
			margin: 20rpx auto;
		}

		.info {
			position: absolute;
			top: 120rpx;
			left: 0;
			right: 0;
			margin: 0 auto;
		}

		.swiper-item {
			text-align: center;
			justify-content: center;
			color: #A71F24;
			font-size: 27rpx;

			.laba {
				width: 27rpx;
				height: 27rpx;
				margin-right: 16rpx;
			}
		}

		.content {
			width: 300rpx;
			height: 120rpx;
			margin: auto;
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 20rpx;
			overflow: hidden;
			margin-top: 20rpx;

			.value {
				color: red;
				font-size: 32rpx;
				font-weight: bold;
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.prize-box {
			background-color: #FFE9C8;
			margin-top: 88rpx;
			border-radius: 20rpx;
			padding: 32rpx;

			.prize-label {
				color: #8B501F;
				text-align: center;
				font-weight: bold;
			}

			.prize-item {
				width: 25%;
				font-size: 24rpx;
				text-align: center;
				color: #835D2D;
				margin: 16rpx 0;

				image {
					width: 67rpx;
					height: 67rpx;
					display: block;
					margin: 0 auto;
					border-radius: 50%;
					background-color: #FFF;
				}
			}
		}
	}
</style>
